import React, { Component } from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import { Button, Modal, Input, Radio, Select, Switch, TreeSelect, message, Icon } from "antd";
import { knowledgeTenantQaCategory, knowledgeImportByTemplate } from '@/services/knowledgemanagement';
const { TreeNode } = TreeSelect;
import styles from "./index.less"
import UserSession from "@/UserSession";

class ReferenceTemplate extends Component {
	constructor(props) {
		super(props);
		this.state = {
			visible: false,
			knowledgeId: '',
			radioValue: false,
			importQa: true,
			categoryQaList: [],
			categoryQaValue: '',
			importAtlas: true,
			categoryAtlasList: [],
			categoryAtlasValue: '',
			importDialog: true,
			categoryDialogList: [],
			categoryDialogValue: '',
			importFile: true,
			categoryFileList: [],
			categoryFileValue: '',
			loading: false,
		};
	}

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this)
		};
	}

	init = id => {
		this.setState({ visible: true, knowledgeId: id }, () => this.getTreeList());
	}

	getTreeList = async () => {
		let res = await knowledgeTenantQaCategory();
		console.log(res);
		this.setState({
			categoryQaValue: res.qaCategory && res.qaCategory.length > 0 ? res.qaCategory[0].qaCategoryId : '',
			categoryAtlasValue: res.atlasCategory && res.atlasCategory.length > 0 ? res.atlasCategory[0].qaCategoryId : '',
			categoryDialogValue: res.dialogCategory && res.dialogCategory.length > 0 ? res.dialogCategory[0].qaCategoryId : '',
			categoryFileValue: res.docCategory && res.docCategory.length > 0 ? res.docCategory[0].qaCategoryId : '',
			categoryQaList: res.qaCategory,
			categoryAtlasList: res.atlasCategory,
			categoryDialogList: res.dialogCategory,
			categoryFileList: res.docCategory,
		})
	}

	onCreate = () => {
		const {
			radioValue, importQa, categoryQaValue, importAtlas, categoryAtlasValue,
			importDialog, categoryDialogValue, importFile, categoryFileValue, knowledgeId
		} = this.state;
		if (radioValue) {
			if (importQa && categoryQaValue === '') return;
			if (importAtlas && categoryAtlasValue === '') return;
			if (importDialog && categoryDialogValue === '') return;
		};
		this.setState({ loading: true }, async () => {
			let obj = null;
			let res = { data: false, msg: formatMessage({ id: 'systemKnowledgeBase.operationFailed' }) };
			if (!radioValue) {
				obj = {
					importAll: !radioValue,
					templateRootCategoryId: knowledgeId,
				};
				res = await knowledgeImportByTemplate(obj);
			} else {
				obj = {
					importAll: !radioValue,
					templateRootCategoryId: knowledgeId,
					targetQaRootCategoryId: radioValue && importQa ? categoryQaValue : '',
					targetAtlasRootCategoryId: radioValue && importAtlas ? categoryAtlasValue : '',
					targetDialogRootCategoryId: radioValue && importDialog ? categoryDialogValue : '',
					targetDocRootCategoryId: radioValue && importFile ? categoryFileValue : '',
					importQa,
					importAtlas,
					importDialog,
					importDoc: importFile,
				};
				res = await knowledgeImportByTemplate(obj);
			};
			if (res?.data) {
				this.setState({ loading: false }, () => {
					this.onCancel();
					message.success(formatMessage({ id: 'systemKnowledgeBase.operationSuccess' }));
				});
			}else{
        this.setState({
          loading:false
        })
      }
		})
	}
	onCancel = () => {
		this.setState({
			visible: false,
			knowledgeId: '',
			radioValue: false,
			importQa: true,
			categoryQaList: [],
			categoryQaValue: '',
			importAtlas: true,
			categoryAtlasList: [],
			categoryAtlasValue: '',
			importDialog: true,
			categoryDialogList: [],
			categoryDialogValue: '',
			importFile: true,
			categoryFileList: [],
			categoryFileValue: '',
		});
	}

	isAllChange = (e) => {
		console.log('radio checked', e.target.value);
		this.setState({ radioValue: e.target.value }, () => {
			// if (e.target.value) {
			// 	this.getTreeList();
			// }
		});
	};

	onQaChange = (checked) => {
		console.log(`switch to ${checked}`);
		this.setState({ importQa: checked });
	};

	onQaChangeCategory = (value) => {
		// console.log(value);
		this.setState({ categoryQaValue: value });
	};

	renderTreeQa = (data) => {
		console.log(data);
		return data.map((item) => {
			if (item.qaCategoryInfoArr) {
				return (
					<TreeNode title={item.qaCategoryName} key={item.qaCategoryId} value={item.qaCategoryId} id={item.qaCategoryId}>{this.renderTreeQa(item.qaCategoryInfoArr)}</TreeNode>
				);
			};
			return (
				<TreeNode title={item.qaCategoryName} key={item.qaCategoryId} value={item.qaCategoryId} id={item.qaCategoryId} />
			);
		});
	};

	onAtlasChange = (checked) => {
		console.log(`switch to ${checked}`);
		this.setState({ importAtlas: checked });
	};

	onAtlasChangeCategory = (value) => {
		// console.log(value);
		this.setState({ categoryAtlasValue: value });
	};

	renderTreeAtlas = (data) => {
		return data.map((item) => {
			if (item.atlasCategoryInfoArr) {
				return (
					<TreeNode title={item.qaCategoryName} key={item.qaCategoryId} value={item.qaCategoryId} id={item.qaCategoryId}>{this.renderTreeAtlas(item.atlasCategoryInfoArr)}</TreeNode>
				);
			};
			return (
				<TreeNode title={item.qaCategoryName} key={item.qaCategoryId} value={item.qaCategoryId} id={item.qaCategoryId} />
			);
		});
	};

	onDialogChange = (checked) => {
		console.log(`switch to ${checked}`);
		this.setState({ importDialog: checked });
	};

	onDialogChangeCategory = (value) => {
		// console.log(value);
		this.setState({ categoryDialogValue: value });
	};

	renderTreeDialog = (data) => {
		return data.map((item) => {
			if (item.dialogCategoryInfoArr) {
				return (
					<TreeNode title={item.qaCategoryName} key={item.qaCategoryId} value={item.qaCategoryId} id={item.qaCategoryId}>{this.renderTreeDialog(item.dialogCategoryInfoArr)}</TreeNode>
				);
			};
			return (
				<TreeNode title={item.qaCategoryName} key={item.qaCategoryId} value={item.qaCategoryId} id={item.qaCategoryId} />
			);
		});
	};

	onFileChange = (checked) => {
		console.log(`switch to ${checked}`);
		this.setState({ importFile: checked });
	};

	onFileChangeCategory = (value) => {
		// console.log(value);
		this.setState({ categoryFileValue: value });
	};


	renderTreeFile = (data) => {
		return data.map((item) => {
			if (item.docCategoryInfoArr) {
				return (
					<TreeNode title={item.qaCategoryName} key={item.qaCategoryId} value={item.qaCategoryId} id={item.qaCategoryId}>{this.renderTreeFile(item.docCategoryInfoArr)}</TreeNode>
				);
			};
			return (
				<TreeNode title={item.qaCategoryName} key={item.qaCategoryId} value={item.qaCategoryId} id={item.qaCategoryId} />
			);
		});
	};

	render() {
		const {
			visible, loading, radioValue,
			importQa, categoryQaList,
			importAtlas, categoryAtlasList,
			importDialog, categoryDialogList,
			importFile, categoryFileList,
		} = this.state;

		return (
			<Modal
				visible={visible}
				title={formatMessage({ id: 'systemKnowledgeBase.referenceTemplate' })}
				okText={formatMessage({ id: 'systemKnowledgeBase.confirm' })}
				cancelText={formatMessage({ id: 'systemKnowledgeBase.cancel' })}
				onCancel={this.onCancel}
				// onOk={this.onCreate}
				destroyOnClose
				footer={[
					<Button onClick={this.onCancel} type="primary" ghost >{formatMessage({ id: 'systemKnowledgeBase.cancel' })}</Button>,
					<Button type="primary" loading={loading} onClick={this.onCreate}>{formatMessage({ id: 'systemKnowledgeBase.confirm' })}</Button>
				]}
				width={720}
			>
				<div className={styles.referBgBox} style={{ borderRadius: '10px', padding: '16px', marginBottom: 16 }}>
					<div style={{ marginBottom: 10 }}>{formatMessage({ id: 'systemKnowledgeBase.referenceWholeKnowledgeBaseDesc' })}</div>
					<div>{formatMessage({ id: 'systemKnowledgeBase.referenceSingleTypeDesc' })}</div>
				</div>
				<div>
					<div style={{ display: 'flex' }}>
						<label style={{ margin: '0px 16px' }}>{formatMessage({ id: 'systemKnowledgeBase.selectReferenceMode' })}</label>
						<Radio.Group onChange={this.isAllChange} value={radioValue}>
							<Radio value={false}>{formatMessage({ id: 'systemKnowledgeBase.importAll' })}</Radio>
							<Radio value={true}>{formatMessage({ id: 'systemKnowledgeBase.referenceSingleType' })}</Radio>
						</Radio.Group>
					</div>
					{radioValue ? (
						<div>
							<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-start', margin: '20px 0' }}>
								<label style={{ margin: '0px 16px' }}>{formatMessage({ id: 'systemKnowledgeBase.qaKnowledge' })}</label>
								<Switch checked={importQa} onChange={this.onQaChange} />
								<div style={{ width: "220px", height: '32px', lineHeight: '32px', marginLeft: 20 }}>
									{importQa ? (
										<>
											<TreeSelect
												style={{ width: '100%' }}
												dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
												placeholder={formatMessage({ id: 'systemKnowledgeBase.selectQaCategory' })}
												allowClear
												value={this.state.categoryQaValue}
												showCheckedStrategy='SHOW_PARENT'
												treeNodeFilterProp='title'
												onChange={this.onQaChangeCategory}
												suffixIcon={<Icon type="caret-down" />}
											>
												{this.renderTreeQa(categoryQaList)}
											</TreeSelect>
										</>
									) : null}
								</div>
							</div>
							{categoryQaList && categoryQaList.length > 0 ? null : (
								<div style={{ margin: '-12px 0px 10px 186px', fontSize: '14px', color: 'red' }}>
									<div>{formatMessage({ id: 'systemKnowledgeBase.noKnowledgeBaseTip' })}</div>
								</div>
							)}
							{
								UserSession.hasAtlasKnowledge() ? (
									<div>
										<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-start', marginBottom: 20 }}>
											<label style={{ margin: '0px 16px' }}>{formatMessage({ id: 'systemKnowledgeBase.mapKnowledge' })}</label>
											<Switch checked={importAtlas} onChange={this.onAtlasChange} />
											<div style={{ width: "220px", height: '32px', lineHeight: '32px', marginLeft: 20 }}>
												{importAtlas ? (
													<TreeSelect
														style={{ width: '100%' }}
														dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
														placeholder={formatMessage({ id: 'systemKnowledgeBase.selectMapCategory' })}
														allowClear
														value={this.state.categoryAtlasValue}
														showCheckedStrategy='SHOW_PARENT'
														treeNodeFilterProp='title'
														onChange={this.onAtlasChangeCategory}
														suffixIcon={<Icon type="caret-down" />}
													>
														{this.renderTreeAtlas(categoryAtlasList)}
													</TreeSelect>
												) : null}
											</div>
										</div>

										{categoryAtlasList && categoryAtlasList.length > 0 ? null : (
											<div style={{ margin: '-12px 0px 10px 186px', fontSize: '14px', color: 'red' }}>
												<div>当前知识中心还没有知识库，请创建后引用。</div>
											</div>
										)}
									</div>
								) : ''
							}

							{
								UserSession.hasDialogKnowledge() ? (
									<div>
										<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-start' }}>
											<label style={{ margin: '0px 16px' }}>{formatMessage({ id: 'systemKnowledgeBase.multiturnKnowledge' })}</label>
											<Switch checked={importDialog} onChange={this.onDialogChange} />
											<div style={{ width: "220px", height: '32px', lineHeight: '32px', marginLeft: 20 }}>
												{importDialog ? (
													<TreeSelect
														style={{ width: '100%' }}
														dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
														placeholder={formatMessage({ id: 'systemKnowledgeBase.selectMultiturnCategory' })}
														allowClear
														value={this.state.categoryDialogValue}
														showCheckedStrategy='SHOW_PARENT'
														treeNodeFilterProp='title'
														onChange={this.onDialogChangeCategory}
														suffixIcon={<Icon type="caret-down" />}
													>
														{this.renderTreeDialog(categoryDialogList)}
													</TreeSelect>
												) : null}
											</div>
										</div>
										{categoryDialogList && categoryDialogList.length > 0 ? null : (
											<div style={{ margin: '0px 0px 10px 186px', fontSize: '14px', color: 'red' }}>
												<div>当前知识中心还没有知识库，请创建后引用。</div>
											</div>
										)}
									</div>
								) : ''
							}

							<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-start', margin: '20px 0' }}>
								<label style={{ margin: '0px 16px' }}>{formatMessage({ id: 'systemKnowledgeBase.documentKnowledge' })}</label>
								<Switch checked={importFile} onChange={this.onFileChange} />
								<div style={{ width: "220px", height: '32px', lineHeight: '32px', marginLeft: 20 }}>
									{importFile ? (
										<>
											<TreeSelect
												style={{ width: '100%' }}
												dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
												placeholder={formatMessage({ id: 'systemKnowledgeBase.selectDocumentCategory' })}
												allowClear
												value={this.state.categoryFileValue}
												showCheckedStrategy='SHOW_PARENT'
												treeNodeFilterProp='title'
												onChange={this.onFileChangeCategory}
												suffixIcon={<Icon type="caret-down" />}
											>
												{this.renderTreeFile(categoryFileList)}
											</TreeSelect>
										</>
									) : null}
								</div>
							</div>
							{categoryQaList && categoryQaList.length > 0 ? null : (
								<div style={{ margin: '-12px 0px 10px 186px', fontSize: '14px', color: 'red' }}>
									<div>当前知识中心还没有知识库，请创建后引用。</div>
								</div>
							)}

						</div>
					) : null}
				</div>
			</Modal>
		);
	}
};

export default ReferenceTemplate;
